package jogs.net;
import jogs.core.*;

import java.lang.Thread;
import java.net.*;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
//import jogs.games.*;

public class TogServer extends Thread
{
	private ServerSocket servsock;
	private GameServer   parent;
	private boolean 	listen;
	//private Game 		game;
	//private static final Logger logger = Logger.getLogger(Player.class.getName());  /** The {@link Logger} for this class. Will fix this back later.. */
	private static final DummyLogger logger = new DummyLogger(); 

	public static Handler handler = new ConsoleHandler();
	static
    {
    	logger.addHandler(handler);
    }
	 
	public TogServer(int port, GameServer p)
	{
		try
		{
			//game = p.getGame();
			servsock = new ServerSocket(port);
			listen = true;
			parent = p; 
		}
		catch(Exception e)
		{
			logger.log(Level.WARNING, "Server on port " + port + " was unable to start\n" + e.toString());
		}
	 }
	 
	public void run()
	{
		try
		{
      System.out.println("TogsServer started. Listening for new connections."); 
			while(listen)
			{
				Socket newcon = servsock.accept();
				Player newPlayer = new Player(newcon, parent);
				//game.join(newPlayer);//change so only add to game after name is given
				newPlayer.start();
				logger.log(Level.INFO, "New Connection");
        System.out.println("Got new connection from " + newcon.toString()); 
			}
			//servsock.close();
			parent = null;
			//game = null;
			servsock = null;
		}
		catch (Exception e)
		{
			if(listen)
				logger.log(Level.WARNING, "problem waiting for connection\n" + e.toString());
			else
				logger.log(Level.INFO, "Closing server\n");
		}
	 }
	 
	public void close()
	{
		listen = false;
		try
		{
			servsock.close();
		}
		catch(Exception e)
		{
			logger.log(Level.WARNING, "problems closing server\n" + e.toString());
		}
	}
}
